//
//  TL_UserDataViewController.m
//  WXReader
//
//  Created by Andrew on 2018/7/17.
//  Copyright © 2018年 Andrew. All rights reserved.
//

#import "TL_UserDataViewController.h"
#import "TL_BindPhoneViewController.h"
#import "TL_CancelAccountViewController.h"

#import "TL_UserDataTableViewCell.h"
#import "TL_UserDataHeaderView.h"

#import "TL_UserDataModel.h"

#import "TL_FacebookManager.h"
#import "TL_GoogleManager.h"
#import "AppDelegate.h"
#import "TLLogoutView.h"
typedef NS_ENUM(NSUInteger, TL_UserInfoStyle) {
    TL_UserInfoStyleName,
    TL_UserInfoStyleGender
};

@interface TL_UserDataViewController () <UITableViewDataSource, UITableViewDelegate, UIActionSheetDelegate,TL_FacebookManagerDelegate, TL_GoogleManagerDelegate>

@property (nonatomic, strong) TL_UserDataModel *userDataModel;

@property (nonatomic, strong) TL_UserDataHeaderView *headerView;

@property (nonatomic, strong) UIView *lOView;
@property (nonatomic, strong) TLLogoutView *logoutCView;

@end

@implementation TL_UserDataViewController
- (UIView *)lOView{
    if (!_lOView) {
        _lOView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        _lOView.backgroundColor = [UIColor colorWithWhite:0 alpha:0];
        
        TLLogoutView *ctV = [TLLogoutView createView];
        ctV.frame = CGRectMake(0, 0, kScreenWidth-38*2, 240);
        ctV.center = CGPointMake(_lOView.center.x, kScreenHeight+self.logoutCView.frame.size.height);
        ctV.cancelBlock = ^{
            [self hiddenLogoutView];
        };
        ctV.doneBlock = ^{
            [self checkLogoutAction];
        };
        [_lOView addSubview:ctV];
        _logoutCView = ctV;
        [ctV layoutIfNeeded];
    }
    return _lOView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initialize];
    [self createSubviews];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self netRequest];
    [self setStatusBarDefaultStyle];
}

- (void)initialize {
    [self setNavigationBarTitle:WXLocalizedString(@"个人信息")];
    
    [TL_FacebookManager sharedManager].delegate = self;

    [TL_GoogleManager sharedManager].delegate = self;
}

- (void)createSubviews {
    self.view.backgroundColor = kGrayViewColor;
    
    self.mainTableViewGroup.delegate = self;
    self.mainTableViewGroup.dataSource = self;
    [self.view addSubview:self.mainTableViewGroup];
    
    [self.mainTableViewGroup mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.top.mas_equalTo(PUB_NAVBAR_HEIGHT);
        make.height.mas_equalTo(SCREEN_HEIGHT - PUB_NAVBAR_HEIGHT);
        make.width.mas_equalTo(SCREEN_WIDTH);
    }];
    
    self.headerView = [[TL_UserDataHeaderView alloc] init];
    self.headerView.backgroundColor = kWhiteColor;
    self.mainTableViewGroup.tableHeaderView = self.headerView;
    
    MK_WEAK_SELF
    
    self.headerView.changeAvatarBlock = ^(UIImage * _Nonnull avatar) {
        if (weakSelf.avatarBlock) {
            weakSelf.avatarBlock(avatar);
        }
        [weakSelf netRequest];
    };
    self.headerView.ImgStrBlock = ^(NSString *text) {
        [weakSelf setUserInfoNetRequestWithStyle:TL_UserInfoStyleGender url:[APIURLManager changeUserInfo] parametersKey:@"headPic" parametersValue:text editedImage:nil];
    };
    
    [self.headerView setUserHeadPic];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section==0) {
        return 2;
    }else if (section==1) {
        return 1;
    }else if (section == 2){
        return 3;
    }else{
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TL_UserDataTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TL_UserDataTableViewCell"];
    
    if (!cell) {
        cell = [[TL_UserDataTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TL_UserDataTableViewCell"];
    }
    
    if (indexPath.section==0) {
        if (indexPath.row == 0) {
            [cell setTitle:@"NickName" andDesc:TL_UserInfoManager.userInfo.nickName andIsShowMore:NO];
        }else if (indexPath.row == 1) {
            NSString *genderStr = @"";
            if ([TL_UserInfoManager.userInfo.gender isEqualToString:@"0"]) {
                genderStr = @"male";
            }else if ([TL_UserInfoManager.userInfo.gender isEqualToString:@"1"]) {
                genderStr = @"female";
            }else{
                genderStr = @"unknown";
            }
            
            [cell setTitle:@"Gender" andDesc:genderStr andIsShowMore:NO];
        }
    }
    
    if (indexPath.section == 1) {
        [cell setTitle:@"ID" andDesc:TL_UserInfoManager.userInfo.userCardId andIsShowMore:NO];
    }
    
    if (indexPath.section == 2) {
        
        if (indexPath.row==0) {
            
            if (TL_UserInfoManager.userInfo.socialEmailVO) {
                [cell setTitle:@"MailBox" andDesc:TL_UserInfoManager.userInfo.socialEmailVO.name andIsShowMore:NO];
            }else{
                [cell setTitle:@"MailBox" andDesc:@"Unbound" andIsShowMore:YES];
            }
            
        }else if (indexPath.row==1){
            
            if (TL_UserInfoManager.userInfo.socialFBVO) {
                [cell setTitle:@"Facebook" andDesc:TL_UserInfoManager.userInfo.socialFBVO.name andIsShowMore:NO];
            }else{
                [cell setTitle:@"Facebook" andDesc:@"Unbound" andIsShowMore:YES];
            }
            
        }else if (indexPath.row==2){
            
            if (TL_UserInfoManager.userInfo.socialGoogleVO) {
                [cell setTitle:@"Google" andDesc:TL_UserInfoManager.userInfo.socialGoogleVO.name andIsShowMore:NO];
            }else{
                [cell setTitle:@"Google" andDesc:@"Unbound" andIsShowMore:YES];
            }
            
        }
    }
    
    if (indexPath.section == 3) {
        [cell setTitle:@"Delete Account" andDesc:@"" andIsShowMore:NO];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString *skipType = @"";
    
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            skipType = Jump_modifyNickname;
        }else if (indexPath.row == 1) {
            skipType = Jump_modifyGender;
        }
    }else if(indexPath.section == 2){
        
        if (indexPath.row == 0) {
            
            skipType = Jump_bindMailbox;
            
            if (TL_UserInfoManager.userInfo.socialEmailVO) {
                return;
            }
        }else if(indexPath.row == 1){
            skipType = Jump_bindFacebook;
            
            if (TL_UserInfoManager.userInfo.socialFBVO) {
                return;
            }
            
        }else if(indexPath.row == 2){
            skipType = Jump_bindGoogle;
            
            if (TL_UserInfoManager.userInfo.socialGoogleVO) {
                return;
            }
            
        }
        
    }else if (indexPath.section == 3){
        
        [self logoutAction];
        return;
    }
    
//    Jump_modifyGender
    [TL_JumpManager jumpActionWithType:skipType content:@"" otherParameter:@{@"title" : @""} completion:^(BOOL isSuccess, NSString * _Nonnull skipType, id  _Nullable object) {
        if (!isSuccess) return;
        
        NSLog(@"%@ - %@",skipType,object);
        
        if ([skipType isEqualToString:Jump_modifyNickname]) {
            [self setUserInfoNetRequestWithStyle:TL_UserInfoStyleName url:[APIURLManager changeUserInfo] parametersKey:@"nickName" parametersValue:object editedImage:nil];
            return;
        }
        
        if ([skipType isEqualToString:Jump_modifyGender]) {
            [self setUserInfoNetRequestWithStyle:TL_UserInfoStyleGender url:[APIURLManager changeUserInfo] parametersKey:@"gender" parametersValue:object editedImage:nil];
            return;
        }
        
        if ([skipType isEqualToString:Jump_bindMailbox]) {
            [kMainWindow showTextHUD:WXLocalizedString(@"绑定成功") afterDelay:2];
            [self netRequest];
            return;
        }
        if ([skipType isEqualToString:Jump_bindFacebook]) {
            [kMainWindow showTextHUD:WXLocalizedString(@"绑定成功") afterDelay:2];
            [self netRequest];
            return;
        }
    }];
}

//section头部间距
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kHalfMargin;
}
//section头部视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, kHalfMargin)];
    view.backgroundColor = kGrayViewColor;
    return view;
}

//section底部间距
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

//section底部视图
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, kHalfMargin)];
    view.backgroundColor = kGrayViewColor;
    return view;
}

- (void)setUserInfoNetRequestWithStyle:(TL_UserInfoStyle)style url:(NSString *)url parametersKey:(NSString *)parametersKey parametersValue:(NSString *)parametersValue editedImage:(UIImage *)editedImage {
    MK_WEAK_SELF
    
    [APIManager sendPostRequest:url parameters:@{parametersKey:parametersValue} model:nil success:^(BOOL success, NSDictionary *  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        if (success) {
            switch (style) {
                case TL_UserInfoStyleName: {
                    [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeSuccess alertTitle:WXLocalizedString(@"修改成功")];
                    !weakSelf.nicknameBlock ?: weakSelf.nicknameBlock(parametersValue);
                }
                    break;
                case TL_UserInfoStyleGender: {
                    [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeSuccess alertTitle:WXLocalizedString(@"修改成功")];
                }
                    break;
                default:
                    break;
            }
        } else {
            [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:requestModel.msg];
        }
        
        [weakSelf netRequest];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
}

#pragma mark TL_FacebookManagerDelegate
- (void)facebookLoginSuccess:(TL_FacebookManager *)manager userInfo:(TL_UserInfoManager *)userInfo {
    [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeSuccess alertTitle:WXLocalizedString(@"绑定成功")];
    [self netRequest];
}

- (void)facebookLoginFail:(TL_FacebookManager *)manager error:(NSString *)error {
    [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:error ?: WXLocalizedString(@"绑定失败")];
}

#pragma mark TL_GoogleManagerDelegate
- (void)googleLoginSuccess:(TL_GoogleManager *)manager userInfo:(TL_UserInfoManager *)userInfo {
    [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeSuccess alertTitle:WXLocalizedString(@"绑定成功")];
    [self netRequest];
}

- (void)googleLoginFail:(TL_GoogleManager *)manager error:(NSString *)error {
    [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:error ?: WXLocalizedString(@"绑定失败")];
}

- (void)netRequest {
    
    if (!TL_UserInfoManager.isLogin) {
        return;
    }
    
    MK_WEAK_SELF
    
    [APIManager sendGetRequest:[APIURLManager getUserInfo] parameters:nil model:TL_UserInfoModel.class success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        
        if (success) {
            NSLog(@"%@",requestModel);
            
            TL_UserInfoModel *usermodel = [TL_UserInfoModel mj_objectWithKeyValues:requestModel.data[@"userInfo"]];

            NSDictionary *userDataDict = [usermodel mj_keyValues];
            
            [[NSUserDefaults standardUserDefaults] setObject:userDataDict forKey:@"UserInfoModelDict"];
            
            TL_UserInfoManager.updateWithDict(requestModel.data[@"userInfo"]);
            
            [weakSelf.mainTableViewGroup reloadData];
            
        } else {
            [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:requestModel.msg ?: WXLocalizedString(@"请求失败")];
            if (requestModel.code == 302) {
                [TL_UserInfoManager logout];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
}

- (void)logoutAction{
    
    [self showLogoutView];
    
}
- (void)showLogoutView{
    
    UIWindow *mainWindow = [UIApplication sharedApplication].keyWindow;
    [mainWindow addSubview:self.lOView];
    
    [UIView animateWithDuration:0.3 animations:^{
        [self.lOView setBackgroundColor:[UIColor colorWithWhite:0 alpha:0.5]];
        self.logoutCView.center = self.lOView.center;
    }];
}
- (void)hiddenLogoutView{
    
    [UIView animateWithDuration:0.3 animations:^{
        [self.lOView setBackgroundColor:[UIColor colorWithWhite:0 alpha:0]];
        self.logoutCView.center = CGPointMake(self.lOView.center.x, kScreenHeight+self.logoutCView.frame.size.height);
    }completion:^(BOOL finished) {
        [self.lOView removeFromSuperview];
    }];
    
}
- (void)checkLogoutAction{
    [self hiddenLogoutView];
    
    [APIManager sendPostRequest:[APIURLManager userWriteOff] parameters:@{} model:nil success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        if (success) {
            [TL_UserInfoManager logout];
            [self.navigationController popViewControllerAnimated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [TL_TopAlertManager showAlertWithError:error defaultText:nil];
    }];
    
}
@end
